import { app, shell, BrowserWindow, ipcMain, clipboard, nativeImage, dialog } from 'electron'
import log from 'electron-log'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'
import { autoUpdater } from 'electron-updater' // 只使用 electron-updater 的 autoUpdater
import { isLoggedIn } from './auth'

// 确保设置正确的环境变量
if (!process.env.NODE_ENV) {
  process.env.NODE_ENV = is.dev ? 'development' : 'production'
}

// const electronStore = new ElectronStore()

function createWindow(): void {
  const startPath = isLoggedIn() ? 'calculator' : 'login'

  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 1000, // 设置窗口的初始宽度
    height: 780, // 可以设置一个初始高度，用户后续可以调整
    minWidth: 1000, // 设置窗口的最小宽度，以确保宽度不小于固定宽度
    maxWidth: 1000, // 设置窗口的最小宽度，以确保宽度不小于固定宽度
    minHeight: 780, // 设置窗口的最小高度，以确保高度不小于固定高度
    resizable: true, // 防止用户调整窗口大小
    show: false,
    autoHideMenuBar: true,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false,
      nodeIntegration: false
    }
  })
  // // 隐藏菜单栏，并且按下 Alt 也不会弹出
  mainWindow.setMenu(null)
  mainWindow.setAutoHideMenuBar(true)

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(`${process.env['ELECTRON_RENDERER_URL']}#/${startPath}`)
  } else {
    mainWindow.loadFile(join(__dirname, `../renderer/index.html`), {
      hash: `/${startPath}`
    })
  }

  // 配置应用日志
  // 配置自动更新日志
  autoUpdater.logger = log
  autoUpdater.autoDownload = true
  log.info('应用启动')

  // 生产环境下启用自动更新
  if (process.env.NODE_ENV === 'production') {
    // 显示当前环境的对话框
    // dialog.showMessageBox({
    //   type: 'info',
    //   title: '环境信息',
    //   message: `当前运行环境: ${process.env.NODE_ENV}`,
    //   buttons: ['确定']
    // })

    // 配置更新服务器
    autoUpdater.setFeedURL({
      provider: 'generic',
      url: `http://47.103.137.203/jsqupdates/`
    })

    // 设置更新检查错误处理
    autoUpdater.on('error', (error) => {
      log.error('自动更新错误:', error)
      // 不要在开发环境显示错误对话框
      if (!is.dev) {
        dialog.showErrorBox(
          '更新失败',
          `更新过程中发生错误: ${error.message}\n请稍后重试或联系开发者。`
        )
      }
    })

    // // 每小时检查一次更新
    // setInterval(
    //   () => {
    //     autoUpdater.checkForUpdates()
    //   },
    //   60 * 60 * 1000
    // )

    // 立即检查更新
    log.info('开始检查更新')
    try {
      // 记录当前版本号
      log.info(`当前应用版本: ${app.getVersion()}`)
      autoUpdater.checkForUpdates().catch((err) => {
        log.error('检查更新时发生错误:', err)
      })
    } catch (error) {
      log.error('启动更新检查失败:', error)
    }

    // 检查更新事件
    autoUpdater.on('checking-for-update', () => {
      log.info('正在检查更新...')
    })

    // 有可用更新
    autoUpdater.on('update-available', (info) => {
      log.info('发现新版本:', info.version)
      log.info('当前版本:', app.getVersion())
      log.info('更新信息:', info)
    })

    // 没有可用更新
    autoUpdater.on('update-not-available', (info) => {
      log.info('当前已是最新版本')
      log.info('当前版本:', app.getVersion())
      log.info('最新版本信息:', info)
    })

    // 下载进度事件
    autoUpdater.on('download-progress', (progressObj) => {
      let logMessage = `下载速度: ${progressObj.bytesPerSecond}`
      logMessage = `${logMessage} - 已下载 ${progressObj.percent}%`
      logMessage = `${logMessage} (${progressObj.transferred}/${progressObj.total})`
      log.info(logMessage)
    })

    autoUpdater.on('update-downloaded', () => {
      log.info('更新下载完成，准备安装')
      dialog
        .showMessageBox({
          type: 'info',
          title: '安装更新',
          message: '更新下载完成，应用将重启并安装',
          buttons: ['现在重启']
        })
        .then(() => {
          log.info('用户确认重启安装更新')
          autoUpdater.quitAndInstall(false, true)
        })
    })

    // 已在上方定义了错误处理
  }
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  // Set app user model id for windows
  electronApp.setAppUserModelId('com.electron')

  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  // IPC test
  ipcMain.on('ping', () => console.log('pong'))

  ipcMain.handle('copy-image-to-clipboard', (_, base64Image) => {
    const image = nativeImage.createFromDataURL(base64Image)
    clipboard.writeImage(image)
    return 'Image copied to clipboard'
  })

  // ipcMain.on('store-get', (_, key) => {
  //   return electronStore.get(key)
  // })

  // ipcMain.on('store-set', (_, args) => {
  //   console.log('store-set', args)
  //   electronStore.set(args.key, args.value)
  // })
  // ipcMain.on('store-delete', (_, key) => {
  //   electronStore.delete(key)
  // })
  // ipcMain.on('store-clear', () => {
  //   electronStore.clear()
  // })

  // ipcMain.handle('get-data', (_, args) => {
  //   return electronStore.get(args.key)
  // })

  // ipcMain.on('set-data', (_, args) => {
  //   electronStore.set(args.key, args.value)
  // })
  // 自动更新逻辑

  createWindow()

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// // 处理从渲染进程传来的 Base64 数据
// ipcMain.handle('copy-image-to-clipboard', (event, base64Data: string) => {
//   const image = nativeImage.createFromDataURL(base64Data);
//   clipboard.writeImage(image);
//   return 'Image copied to clipboard!';
// });
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// In this file you can include the rest of your app"s specific main process
// code. You can also put them in separate files and require them here.
